<template>
  <div>
    <!-- 搜索区域 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="试卷标题">
        <el-input v-model="searchModel.title" placeholder="请输入试卷标题" clearable />
      </el-form-item>
      <el-form-item label="试卷状态">
        <el-select v-model="searchModel.status" placeholder="请选择状态" clearable>
          <el-option label="草稿" value="draft" />
          <el-option label="已发布" value="published" />
          <el-option label="已归档" value="archived" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getTableData">查询</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button type="success" @click="showAddDialog">新增试卷</el-button>
        <el-button type="warning" @click="goToCompose">组卷管理</el-button>
        <el-button type="danger" :disabled="selectedIds.length == 0" @click="batchDelete">批量删除</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="title" label="试卷标题" width="200" />
      <el-table-column prop="description" label="试卷描述" show-overflow-tooltip />
      <el-table-column prop="questionCount" label="题目数量" width="100" />
      <el-table-column prop="totalScore" label="总分" width="80" />
      <el-table-column prop="duration" label="时长(分钟)" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="getStatusType(scope.row.status)"
            size="small"
          >
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button size="mini" @click="viewDetail(scope.row)">详情</el-button>
          <el-button size="mini" @click="editPaper(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="success"
            v-if="scope.row.status === 'draft'"
            @click="publishPaper(scope.row)"
          >
            发布
          </el-button>
          <el-button
            size="mini"
            type="warning"
            v-if="scope.row.status === 'published'"
            @click="archivePaper(scope.row)"
          >
            归档
          </el-button>
          <el-button size="mini" type="danger" @click="deletePaper(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      :current-page="searchModel.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%">
      <el-form ref="paperForm" :model="paperForm" :rules="paperRules" label-width="100px">
        <el-form-item label="试卷标题" prop="title">
          <el-input v-model="paperForm.title" placeholder="请输入试卷标题" />
        </el-form-item>
        <el-form-item label="试卷描述" prop="description">
          <el-input
            v-model="paperForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入试卷描述"
          />
        </el-form-item>
        <el-form-item label="考试时长" prop="duration">
          <el-input-number
            v-model="paperForm.duration"
            :min="1"
            :max="300"
            placeholder="分钟"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="savePaper">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import paperApi from '@/api/paperApi'

export default {
  data() {
    return {
      searchModel: {
        title: '',
        status: '',
        size: 10,
        page: 1
      },
      total: 0,
      tableData: [],
      selectedIds: [],
      dialogVisible: false,
      dialogTitle: '',
      paperForm: {
        paperId: null,
        title: '',
        description: '',
        duration: 60
      },
      paperRules: {
        title: [
          { required: true, message: '请输入试卷标题', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入试卷描述', trigger: 'blur' }
        ],
        duration: [
          { required: true, message: '请输入考试时长', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getTableData()
  },
  methods: {
    // 获取表格数据
    getTableData() {
      paperApi.getPageData(this.searchModel).then(res => {
        this.tableData = res.data.papers
        this.total = res.data.total
      })
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.searchModel.pageSize = size
      this.getTableData()
    },

    // 当前页变化
    handleCurrentChange(page) {
      this.searchModel.currentPage = page
      this.getTableData()
    },

    // 重置搜索
    reset() {
      this.searchModel.title = ''
      this.searchModel.status = ''
      this.getTableData()
    },

    // 多选框选择
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.paperId)
    },

    // 显示新增对话框
    showAddDialog() {
      this.dialogTitle = '新增试卷'
      this.paperForm = {
        paperId: null,
        title: '',
        description: '',
        duration: 60
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.paperForm.clearValidate()
      })
    },

    // 编辑试卷
    editPaper(row) {
      this.dialogTitle = '编辑试卷'
      this.paperForm = {
        paperId: row.paperId,
        title: row.title,
        description: row.description,
        duration: row.duration
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.paperForm.clearValidate()
      })
    },

    // 保存试卷
    savePaper() {
      this.$refs.paperForm.validate((valid) => {
        if (valid) {
          paperApi.save(this.paperForm).then(res => {
            if (res.code === 200) {
              this.$message.success(res.message)
              this.dialogVisible = false
              this.getTableData()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },

    // 查看详情
    viewDetail(row) {
      this.$router.push(`/paper/detail/${row.paperId}`)
    },

    // 发布试卷
    publishPaper(row) {
      this.$confirm('确定要发布此试卷吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        paperApi.publish(row.paperId).then(res => {
          this.$message.success(res.message)
          this.getTableData()
        })
      })
    },

    // 归档试卷
    archivePaper(row) {
      this.$confirm('确定要归档此试卷吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        paperApi.archive(row.paperId).then(res => {
          this.$message.success(res.message)
          this.getTableData()
        })
      })
    },

    // 删除试卷
    deletePaper(row) {
      this.$confirm(`确定要删除试卷"${row.title}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        paperApi.delete(row.paperId).then(res => {
          this.$message.success(res.message)
          this.getTableData()
        })
      })
    },

    // 批量删除
    batchDelete() {
      this.$confirm('确定要批量删除选中的试卷吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        paperApi.batchDelete(this.selectedIds).then(res => {
          this.$message.success(res.message)
          this.getTableData()
        })
      })
    },

    // 获取状态类型
    getStatusType(status) {
      const typeMap = {
        'draft': 'info',
        'published': 'success',
        'archived': 'warning'
      }
      return typeMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const textMap = {
        'draft': '草稿',
        'published': '已发布',
        'archived': '已归档'
      }
      return textMap[status] || status
    },

    // 跳转到组卷管理页面
    goToCompose() {
      this.$router.push('/paper/compose')
    }
  }
}
</script>

<style scoped>
.demo-form-inline .el-form-item {
  margin-bottom: 20px;
}
</style>
